package net.shopxx.runner;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import net.shopxx.constant.CollectConstant;
import net.shopxx.entity.StockKeepingUnit;
import net.shopxx.entity.TaobaoProduct;
import net.shopxx.service.TaobaoProductService;

@Service("taobaoProductCollectRunner")
public class TaobaoProductCollectRunner implements Runnable {

	/** logger */
	private static final Logger logger = Logger.getLogger(TaobaoProductCollectRunner.class);

	@Resource(name = "taobaoProductServiceImpl")
	private TaobaoProductService taobaoProductService;

	private String ids = "";

	@Override
	public void run() {
		TaobaoProduct tp;
		try {
			for (String id : ids.split(System.getProperty("line.separator"))) {
				if (StringUtils.isBlank(id)) {
					continue;
				} else {
					id = id.trim();
					tp = getTaobaoProduct(Long.parseLong(id));
				}
				if (tp == null) {
					continue;
				} else {
					taobaoProductService.save(tp);
				}
				Thread.sleep(10000);
			}
		} catch (Exception e) {
			logger.error("采集淘宝宝贝发生错误：" + e);
		}

	}

	private TaobaoProduct getTaobaoProduct(Long id) {
		Document doc = null;
		String desc = "";
		String title = "";
		String skuJson = "";
		String imgs = "";
		String reg = null;
		Matcher matcher = null;
		Pattern pattern = null;

		try {
			doc = Jsoup.connect("https://item.taobao.com/item.htm?id=" + id).get();
			// 获取标题信息
			title = doc.select("#J_Title h3").text();

			if (StringUtils.isBlank(title)) {
				logger.error(doc.html());
				return null;
			}

			// 获取商品图片
			Iterator<Element> ie = doc.select("#J_UlThumb img").iterator();
			while (ie.hasNext()) {
				Element e = ie.next();
				imgs = imgs + "https://" + e.attr("data-src").replaceAll("_50x50.jpg", "").replaceAll("//", "") + ";";
			}

			// 获取sku标题信息
			Map<String, String> skuMap = new HashMap<String, String>();
			ie = doc.select(".J_TSaleProp li").iterator();
			while (ie.hasNext()) {
				Element e = ie.next();
				skuMap.put(e.attr("data-value"), e.select("span").text());
			}

			Elements scriptElements = doc.select("script");

			// 获取sku价格信息
			reg = "skuMap(.)*(}})";
			pattern = Pattern.compile(reg);
			matcher = pattern.matcher(scriptElements.html());
			if (matcher.find()) {
				skuJson = matcher.group().replaceAll("skuMap     : ", "").replaceAll("\";", "\"").replaceAll(";\"", "\"");
			}
			skuJson = getSkuJson(skuJson, skuMap);

			// 获取描述信息
			reg = "dsc.taobaocdn.com(\\S)*";
			pattern = Pattern.compile(reg);
			matcher = pattern.matcher(scriptElements.html());
			if (matcher.find()) {

				String descUrl = "http://" + matcher.group().replaceAll("'", "");
				doc = Jsoup.connect(descUrl).get();
				Elements descBody = doc.select("body");

				reg = "\n[^']*";
				pattern = Pattern.compile(reg);
				matcher = pattern.matcher(descBody.html());
				if (matcher.find()) {
					desc = matcher.group();
				}
			}
			TaobaoProduct tp = new TaobaoProduct();
			tp.setTaobaoProductId(id);
			tp.setImgs(imgs);
			tp.setTitle(title);
			tp.setIntroduction(desc);
			tp.setSkuJson(skuJson);
			tp.setStatus(CollectConstant.DEFAULT_TAOBAO_PRODUCT_STATUS_INIT);
			return tp;
		} catch (IOException e) {
			logger.error("淘宝宝贝采集错误：" + e);
		}
		return null;
	}

	private String getSkuJson(String skuJson, Map<String, String> skuMap) {
		List<StockKeepingUnit> skuList = new ArrayList<StockKeepingUnit>();
		JSONObject skuObjects = new JSONObject(skuJson);
		Iterator<String> keys = skuObjects.keys();
		while (keys.hasNext()) {
			String key = keys.next();
			JSONObject skuObject = skuObjects.getJSONObject(key);
			BigDecimal skuPrice = skuObject.getBigDecimal("price");
			StockKeepingUnit sku = new StockKeepingUnit(skuPrice, skuMap.get(key));
			sku.setMarketPrice(getMarketPriceBySkuPrice(skuPrice));
			skuList.add(sku);
		}
		JSONArray jsonArray = new JSONArray(skuList);

		return jsonArray.toString();
	}

	/**
	 * 获取通过sku价格默认计算市场价格
	 * 
	 * @param skuPrice
	 * @return
	 */
	private BigDecimal getMarketPriceBySkuPrice(BigDecimal skuPrice) {
		// skuPrice 正常的情况下，用skuPrice计算市场价，否则返回0
		if (skuPrice != null && skuPrice.compareTo(BigDecimal.ZERO) == 1) {
			BigDecimal m = skuPrice.multiply(CollectConstant.DEFAULT_MARKET_INDEX).divide(BigDecimal.TEN, 0, RoundingMode.HALF_DOWN);
			return m.multiply(BigDecimal.TEN).add(getLastNumber(m));
		} else {
			return BigDecimal.ZERO;
		}
	}

	private BigDecimal getLastNumber(BigDecimal m) {
		BigDecimal three = new BigDecimal(3);
		if (m.remainder(three).compareTo(BigDecimal.ZERO) == 0) {
			return new BigDecimal(9);
		} else if (m.remainder(three).compareTo(BigDecimal.ONE) == 0) {
			return new BigDecimal(5);
		} else {
			return new BigDecimal(8);
		}
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

}
